package com.ricchieri.manage.bean;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.jasypt.util.password.ConfigurablePasswordEncryptor;
import org.springframework.security.core.context.SecurityContextHolder;

import com.ricchieri.common.BusinessSettings;
import com.ricchieri.common.CustomAuthenticationToken;
import com.ricchieri.filter.UserFilter;
import com.ricchieri.model.User;
import com.ricchieri.service.interf.IUserService;
import com.ricchieri.util.FacesUtil;

@ManagedBean(name = "changePasswordMB")
@ViewScoped
public class ChangePasswordManageBean extends GenericManageBean {

	private static final long serialVersionUID = 2792148315202960844L;
	
	@ManagedProperty(value = "#{UserService}")
	IUserService userService;
	
	@ManagedProperty(value="#{configurablePasswordEncryptor}")
	ConfigurablePasswordEncryptor encriptor;
	
	private String oldPassword;
	private String newPassword;
	private String newPasswordConfirmation;
	
	public String changePassword() {
		User currentUser = ((CustomAuthenticationToken)SecurityContextHolder.getContext().getAuthentication()).getUser();
		
		UserFilter userFilter = new UserFilter();
		userFilter.setId(currentUser.getId());
		User user = userService.getUserByFilter(userFilter);

		String encriptPassword = encriptor.encryptPassword(oldPassword);
		if (!user.getPassword().equals(encriptPassword)) {
			FacesUtil.addErrorMsg("changePasswordForm:oldPassword", "old_password_is_wrong");
			return BusinessSettings.UNSUCCESS;
		} else {
			user.setPassword(encriptor.encryptPassword(newPassword));
			userService.updateUser(user);
			return BusinessSettings.SUCCESS;
		}
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getNewPasswordConfirmation() {
		return newPasswordConfirmation;
	}

	public void setNewPasswordConfirmation(String newPasswordConfirmation) {
		this.newPasswordConfirmation = newPasswordConfirmation;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public ConfigurablePasswordEncryptor getEncriptor() {
		return encriptor;
	}

	public void setEncriptor(ConfigurablePasswordEncryptor encriptor) {
		this.encriptor = encriptor;
	}	
	
	
}
